package com.example.yunbiji0314.config;

import com.example.yunbiji0314.util.JwtTokenUtil;
import com.example.yunbiji0314.util.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * OncePerRequestFilter
 * Once:一次
 * Per:每个
 * Request：请求
 * Filter:过滤器
 *
 * 前端项目向后端发请求 每个请求都只会过一次的过滤器
 */
@Component
public class MyLoginTestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate ;


    /**
     *
     * @param httpServletRequest  请求对象 前端发来的请求 请求参数 请求头 请求体 全部封装到这个对象中
     * @param httpServletResponse  响应对象  后端给前端响应的数据  响应参数 响应头 响应题 全部在这个对象中
     * @param filterChain  他会存储过滤器链中的所有过滤器 分1,2,3,4,5  1走完
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 从请求头中获取牌牌
        String authorization = httpServletRequest.getHeader("Authorization");
        // 判断请求头中是否有牌牌
        if(authorization==null){
            // 说明是登录
            System.out.println("说明是登录");
        }else{
            System.out.println("不是登录，是其他请求");
            // 如果带了  我们需要进一步验证是否是合法的
            String username = jwtTokenUtil.getUserNameFromToken(authorization);
            if(username!=null){
                // 说明 解析正确
                System.out.println("解析正确");
                // 去redis中取登录这个人的角色和权限
                LoginUser o =(LoginUser) redisTemplate.opsForValue().get(username);


                // 登录对象
//                Collection
//                        <? extends GrantedAuthority>
//                List<GrantedAuthority> quanxians = new ArrayList<>();
                List<String> quanxianandroles = o.getQuanxianandrole();
                // 遍历第二个集合
//                for (String s:quanxianandroles){
//                    GrantedAuthority hh = new SimpleGrantedAuthority(s);
//                    quanxians.add(hh);
//                }

                // stream流
                List<SimpleGrantedAuthority> collect = quanxianandroles.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList());

                UsernamePasswordAuthenticationToken xx = new UsernamePasswordAuthenticationToken(username,o.getPwd(),collect);
                SecurityContext context = SecurityContextHolder.getContext();
                // setAuthentication(需要一个实现了Authentication对象)
                context.setAuthentication(xx);
                System.out.println("xx:"+xx);


            }else{
                // 说明解析失败
                System.out.println("解析失败");
            }
        }

        // 放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
